package blog

import (
	"dustbe/controller/password"
	"dustbe/database"
	"dustbe/util"
	"errors"
	"fmt"
	"net/http"
	"os"
	"strings"

	"github.com/gin-gonic/gin"
)

type ModifyPackage struct {
	Password   string `json:"password"`
	Seq        int    `json:"seq"`
	Name       string `json:"name"`
	Tags       string `json:"tags"`
	AdjustTime string `json:"adjustTime"`
	ImgUrl     string `json:"imgUrl"`
	Text       string `json:"text"`
}

func modifyLocalBlog(seq int, text string) error {
	text = strings.TrimSpace(text)
	if len(text) == 0 {
		return nil
	}
	// 删除原本的博客
	markdownFilePath := fmt.Sprintf("%s/%d.md", blogRoot, seq)
	markdownFilePathExist, _ := util.CheckFilePath(markdownFilePath)
	if markdownFilePathExist {
		err := os.Remove(markdownFilePath)
		if err != nil {
			return errors.New("修改失败（删除本地文件失败）")
		}
	}

	// 将文章输出到本地
	dstFile, err := os.Create(markdownFilePath)
	if err != nil {
		fmt.Println(err.Error())
		return err
	}
	defer dstFile.Close()
	_, err = dstFile.WriteString(text)
	if err != nil {
		return errors.New("markdown写入本地文件出错")
	}
	return nil
}

func ModifyBlogBySeq(c *gin.Context) {
	var modifyPackage ModifyPackage
	err := c.ShouldBindJSON(&modifyPackage)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"data": "请求体不正确"})
		return
	}

	modifyPassword := modifyPackage.Password
	if modifyPassword != password.MyPasswords.ModifyBlog {
		c.JSON(http.StatusNonAuthoritativeInfo, gin.H{"data": "密码错误（modify）"})
		return
	}

	name := modifyPackage.Name
	tags := modifyPackage.Tags
	adjustTime := modifyPackage.AdjustTime
	imgUrl := modifyPackage.ImgUrl
	text := modifyPackage.Text
	seq := modifyPackage.Seq

	// 先获取原本的博客题目
	blogNode, err := database.QueryBlogBySeq(seq)
	if err != nil || len(blogNode) == 0 {
		c.JSON(http.StatusOK, gin.H{"data": "获取原本的博客名称失败"})
		return
	}

	// 修改原本的信息
	suc, _ := database.ModifyBlogBySeq(seq, name, tags, adjustTime, imgUrl, text)
	if !suc {
		c.JSON(http.StatusOK, gin.H{"data": "修改失败（修改数据库信息）"})
		return
	}

	modifyLocalBlog(seq, text)

	c.JSON(http.StatusOK, gin.H{"code": 200, "data": "修改博客成功"})
}
